/**axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from 'axios';
import QS from 'qs';
import { useStore } from '../store'

 // 请求超时时间
axios.defaults.timeout = 10000;
axios.defaults.baseURL = 'https://h5.fortrip.cn/api/form'
// axios.defaults.baseURL = '/api/bt2024'

// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.interceptors.request.use(
  config => {
    const store = useStore()
    const token = store.getToken
    token && (config.headers.TOKEN = token)
    return config
  },
  error => {
    return Promise.error(error)
  })

export function rest(url:string, method:string, data:any): Promise<any> {
  if (method.toLowerCase() == 'get') {
    url += '?' + QS.stringify(data)
  }
  return new Promise((resolve, reject) => {
    axios({
      method: method,
      url: url,
      data: QS.stringify(data),
    }).then(res => {
      resolve(res);
    })
    .catch(err => {
      reject(err)
    })
  })
}

export function get(url: string, data: any) {
  return rest(url, 'get', data)
}
export function post(url: string, data: any) {
  return rest(url, 'post', data)
}

export function patch(url: string, data: any) {
  return rest(url, 'patch', data)
}

export function put(url: string, data: any) {
  return rest(url, 'put', data)
}